﻿
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Public Class udpstream
    Inherits Stream

    Protected Friend client As UdpClient = Nothing
    Protected Friend remoteEP As IPEndPoint = Nothing

    Public Sub New(ByVal localport As Int32, ByVal remoteaddress As String, ByVal remoteport As Int32)
        On Error Resume Next

        client = New UdpClient(localport)
        assert(Not client Is Nothing, "failed to create new instance of client, localport = " _
                                        + Convert.ToString(localport))
        Dim localEP As IPEndPoint = Nothing
        localEP = IPEndpoint2.create(network.localhost, localport)
        client.Client.Bind(localEP)
        remoteEP = IPEndpoint2.create(remoteaddress, remoteport)
    End Sub

    Public Overrides Sub Close()
        On Error Resume Next
        client.Close()
    End Sub

    Public Overrides ReadOnly Property CanRead() As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides ReadOnly Property CanSeek() As Boolean
        Get
            Return False
        End Get
    End Property

    Public Overrides ReadOnly Property CanWrite() As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides Sub Flush()

    End Sub

    Public Overrides ReadOnly Property Length() As Long
        Get
            Return npos
        End Get
    End Property

    Public Overrides Property Position() As Long
        Get
            Return npos
        End Get
        Set(ByVal value As Long)

        End Set
    End Property

    Public Overrides Function Read(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer) As Integer
        Dim receive() As Byte = Nothing
        receive = client.Receive(remoteEP)
        Dim rtn As Int32
        rtn = min(min(count, buffer.Length - offset), receive.Length)
        memcpy(buffer, offset, receive, 0, rtn)
        Return rtn
    End Function

    Public Overrides Function Seek(ByVal offset As Long, ByVal origin As SeekOrigin) As Long
        Return npos
    End Function

    Public Overrides Sub SetLength(ByVal value As Long)

    End Sub

    Public Overrides Sub Write(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer)
        client.Send(buffer, count, remoteEP)
    End Sub
End Class
